package com.xdap.keymen.utils;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class OKHttpUtils {
    private static final MediaType JSON = MediaType.parse("application/json");

    @Autowired
    private OkHttpClient okHttpClient;

    public String doPost(String url) {
        return doPost(url, null, null);
    }

    public String doGetToParams(String url, Map<String, String> params) {
        return doGet(url, params, null);
    }

    public String doGetToHeaders(String url, Map<String, String> headers) {
        return doGet(url, null, headers);
    }

    public String doGet(String url, Map<String, String> params, Map<String, String> headers) {
        Request.Builder builder = new Request.Builder();
        if (headers != null && !headers.isEmpty()) {
            for (String header : headers.keySet()) {
                builder.addHeader(header, headers.get(header));
            }
        }
        Request request = builder.url(buildUrlWithParams(url, params)).build();
        return executeBody(request);
    }


    public String doPostForm(String url, Map<String, String> params) {
        FormBody.Builder builder = new FormBody.Builder();
        if (params != null && !params.keySet().isEmpty()) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
        Request request = new Request.Builder().url(url).post(builder.build()).build();
        return execute(request);
    }

    public String doPost(String url, Map<String, String> params, Map<String, String> headers) {
        FormBody.Builder builder = new FormBody.Builder();
        if (params != null && !params.keySet().isEmpty()) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
        Request.Builder requestBuilder = new Request.Builder();
        if (headers != null && !headers.isEmpty()) {
            for (String header : headers.keySet()) {
                requestBuilder.addHeader(header, headers.get(header));
            }
        }
        Request request = requestBuilder.url(url).post(builder.build()).build();
        return execute(request);
    }

    /**
     * Do post with Json body and Content-Type is application/json.
     *
     * @param url  The request URL.
     * @param json The json body
     * @return Result.
     */
    public String doPostJson(String url, String json) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        return doPostJson(url, json, headers, JSON);
    }

    /**
     * Do post with Json body and Content-Type is application/json.
     *
     * @param url  The request URL.
     * @param json The json body
     * @param type The media type.
     * @return
     */
    public String doPostJson(String url, String json, MediaType type) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        return doPostJson(url, json, headers, type);
    }

    /**
     * Do post with Json body.
     *
     * @param url     The request URL.
     * @param json    The json body
     * @param headers The request headers.
     * @param params  The request params.
     * @return Result.
     */
    public String doPostJson(String url, String json, Map<String, String> headers, Map<String, String> params) {
        return doPostJson(buildUrlWithParams(url, params), json, headers, JSON);
    }

    /**
     * Do post with Json body.
     *
     * @param url     The request URL.
     * @param json    The json body
     * @param headers The request headers.
     * @return Result.
     */
    public String doPostJson(String url, String json, Map<String, String> headers, MediaType mediaType) {
        RequestBody requestBody = RequestBody.create(mediaType, json);
        Request.Builder builder = new Request.Builder();
        if (headers != null && !headers.isEmpty()) {
            for (String header : headers.keySet()) {
                builder.addHeader(header, headers.get(header));
            }
        }
        Request request = builder.url(url).post(requestBody).build();
        return execute(request);
    }

    private String execute(Request request) {
        try (Response response = okHttpClient.newCall(request).execute()) {
            if (response.isSuccessful()) {
                assert response.body() != null;
                return response.body().string();
            }
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
        }
        return StringUtils.EMPTY;
    }

    private String executeBody(Request request) {
        try (Response response = okHttpClient.newCall(request).execute()) {
            if (response.body() != null) {
                return response.body().string();
            }
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
        }
        return StringUtils.EMPTY;
    }

    /**
     * Build request url with params.
     *
     * @param url    The request url
     * @param params The params with inline the  url.
     * @return The whole url.
     */
    private String buildUrlWithParams(String url, Map<String, String> params) {
        StringBuilder sb = new StringBuilder(url);
        if (params != null && !params.keySet().isEmpty()) {
            boolean firstFlag = true;
            for (String key : params.keySet()) {
                if (firstFlag) {
                    sb.append("?").append(key).append("=").append(params.get(key));
                    firstFlag = false;
                } else {
                    sb.append("&").append(key).append("=").append(params.get(key));
                }
            }
        }
        return sb.toString();
    }
}
